﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.JSON;
using System.IO;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Base class for all value controls whose values are JSON (de)serializable.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public abstract class BaseJsonValueControl<T> : BaseComplexValueControl<T>
		where T : class, IJsonCompatible, new()
	{
		/// <summary>
		/// Outputs the value of this control to the specified <see cref="JsonWriter"/>.
		/// </summary>
		/// <param name="jw"></param>
		protected override void SaveValue(JsonWriter jw)
		{
			if (this.Value == null)
				jw.Null();
			else
				this.Value.Serialize(jw);
		}
		/// <summary>
		/// When implemented, gets or sets the serialized value - in the format that is suitable for client-server transfers.
		/// </summary>
		protected internal override string SerializedValue
		{
			get
			{
				using (StringWriter sw = new StringWriter())
				{
					JsonWriter jw = new JsonWriter(sw);

					this.SaveValue(jw);

					return sw.ToString();
				}
			}
			set
			{
				using (StringReader sr = new StringReader(value))
				{
					JsonReader jr = new JsonReader(sr);

					this.DeserializeValue(jr);
				}
			}
		}
		/// <summary>
		/// Deserializes the value of this control from the specified reader.
		/// </summary>
		/// <param name="jr"></param>
		protected virtual void DeserializeValue(JsonReader jr)
		{
			if (jr.TokenType == JsonToken.Null)
				this.Value = null;
			else
			{
				this.Value = new T();
				this.Value.Deserialize(jr);
			}
		}
	}
}
